@extends('layouts.app')

@section('title', '编辑记账')

@section('content')
<div class="page-header">
    <button class="back-btn" onclick="window.location.href = '/'">‹</button>
    <h1 class="page-title">编辑记账</h1>
</div>
<div class="form-container">
    <div class="record-type-tabs">
        <div class="record-type-tab expense {{ $transaction->type == \App\Models\MoneyCategory::TYPE_EXPENSE ? 'active' : '' }}" id="expense-tab">支出</div>
        <div class="record-type-tab income {{ $transaction->type == \App\Models\MoneyCategory::TYPE_INCOME ? 'active' : '' }}" id="income-tab">收入</div>
    </div>

    <form id="transaction-form">
        @csrf
        @method('PUT')
        <input type="hidden" id="transaction-type" name="type" value="{{ $transaction->type == \App\Models\MoneyCategory::TYPE_INCOME ? 'income' : 'expense' }}">
        <input type="hidden" id="transaction-id" value="{{ $transaction->id }}">
        <input type="hidden" id="record-date" name="transaction_date" value="{{ $transaction->transaction_date }}">

        <div class="form-group">
            <label class="form-label">分类</label>

            <!-- 支出分类 -->
            <div class="category-selector" id="expense-categories" style="{{ $transaction->type == \App\Models\MoneyCategory::TYPE_EXPENSE ? 'display: grid' : 'display: none' }}">
                @if(count($expenseCategories) > 0)
                    @foreach($expenseCategories as $cat)
                    <div class="category-item {{ $transaction->category_id == $cat->id ? 'active' : '' }}" data-category="{{ $cat->name }}" data-category-id="{{ $cat->id }}" data-type="expense">
                        <div class="category-icon">{{ $cat->icon }}</div>
                        <div class="category-name">{{ $cat->name }}</div>
                    </div>
                    @endforeach
                @else
                    <div style="grid-column: 1 / -1; text-align: center; color: #999;">暂无支出分类</div>
                @endif
            </div>

            <!-- 收入分类 -->
            <div class="category-selector" id="income-categories" style="{{ $transaction->type == \App\Models\MoneyCategory::TYPE_INCOME ? 'display: grid' : 'display: none' }}">
                @if(count($incomeCategories) > 0)
                    @foreach($incomeCategories as $cat)
                    <div class="category-item {{ $transaction->category_id == $cat->id ? 'active' : '' }}" data-category="{{ $cat->name }}" data-category-id="{{ $cat->id }}" data-type="income">
                        <div class="category-icon">{{ $cat->icon }}</div>
                        <div class="category-name">{{ $cat->name }}</div>
                    </div>
                    @endforeach
                @else
                    <div style="grid-column: 1 / -1; text-align: center; color: #999;">暂无收入分类</div>
                @endif
            </div>

            <!-- 支出二级分类 -->
            @foreach($expenseCategories as $cat)
            @if($cat->subCategories->count() > 0)
            <div class="subcategory-selector" id="subcategory-expense-{{ $cat->id }}" style="{{ $transaction->category_id == $cat->id && $transaction->type == \App\Models\MoneyCategory::TYPE_EXPENSE ? 'display: block' : 'display: none' }}">
                <div class="subcategory-title">{{ $cat->name }} - 二级分类</div>
                <div class="subcategory-box">
                    @foreach($cat->subCategories as $subCat)
                        <div class="subcategory-item {{ $transaction->sub_category_id == $subCat->id ? 'active' : '' }}" data-subcategory="{{ $subCat->name }}" data-subcategory-id="{{ $subCat->id }}">
                            <div class="subcategory-icon">{{ $subCat->icon }}</div>
                            <div class="subcategory-name">{{ $subCat->name }}</div>
                        </div>
                    @endforeach
                </div>
            </div>
            @endif
            @endforeach

            <!-- 收入二级分类 -->
            @foreach($incomeCategories as $cat)
            @if($cat->subCategories->count() > 0)
            <div class="subcategory-selector" id="subcategory-income-{{ $cat->id }}" style="{{ $transaction->category_id == $cat->id && $transaction->type == \App\Models\MoneyCategory::TYPE_INCOME ? 'display: block' : 'display: none' }}">
                <div class="subcategory-title">{{ $cat->name }} - 二级分类</div>
                <div class="subcategory-box">
                @foreach($cat->subCategories as $subCat)
                <div class="subcategory-item {{ $transaction->sub_category_id == $subCat->id ? 'active' : '' }}" data-subcategory="{{ $subCat->name }}" data-subcategory-id="{{ $subCat->id }}">
                    <div class="subcategory-icon">{{ $subCat->icon }}</div>
                    <div class="subcategory-name">{{ $subCat->name }}</div>
                </div>
                @endforeach
                </div>
            </div>
            @endif
            @endforeach

            <div class="category-selected-info" id="category-selected-info" style="{{ $transaction->sub_category_id ? 'display: block' : 'display: none' }}">
                @if($transaction->subCategory)
                    已选: {{ $transaction->category->name }} - {{ $transaction->subCategory->name }}
                @endif
            </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
            <input type="text" class="description-input" id="record-note" name="description" placeholder="添加备注..." value="{{ $transaction->description }}">
            <div class="amount-display" id="amount-display">{{ $transaction->amount }}</div>
            <button type="button" class="receipt-upload" id="receipt-upload">📷</button>
        </div>

        <!-- 计算器 -->
        <div class="calculator">
            <div class="calculator-grid">
                <button type="button" class="calculator-btn" data-value="7">7</button>
                <button type="button" class="calculator-btn" data-value="8">8</button>
                <button type="button" class="calculator-btn" data-value="9">9</button>
                <button type="button" class="calculator-btn date" id="date-btn">📅 <span id="date-display"></span></button>
                <button type="button" class="calculator-btn" data-value="4">4</button>
                <button type="button" class="calculator-btn" data-value="5">5</button>
                <button type="button" class="calculator-btn" data-value="6">6</button>
                <button type="button" class="calculator-btn operator" data-value="+">+</button>

                <button type="button" class="calculator-btn" data-value="1">1</button>
                <button type="button" class="calculator-btn" data-value="2">2</button>
                <button type="button" class="calculator-btn" data-value="3">3</button>
                <button type="button" class="calculator-btn operator" data-value="-">-</button>

                <button type="button" class="calculator-btn" data-value="0">0</button>
                <button type="button" class="calculator-btn" data-value=".">.</button>
                <button type="button" class="calculator-btn" id="delete-btn">⌫</button>
                <button type="button" class="calculator-btn operator" id="saveBtn">完成</button>
            </div>
        </div>
    </form>
</div>

<!-- 日期选择模态框 -->
<div class="modal fade" id="dateModal" tabindex="-1" role="dialog" aria-labelledby="dateModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content modal-test">
            <div class="modal-header">
                <h5 class="modal-title" id="dateModalLabel">选择日期</h5>
                <button class="modal-close" data-dismiss="modal" aria-label="Close">×</button>
            </div>
            <div class="modal-body">
                <div class="date-picker-container">
                    <div class="date-quick-options">
                        <button type="button" class="date-quick-btn" data-days="0">今天</button>
                        <button type="button" class="date-quick-btn" data-days="-1">昨天</button>
                        <button type="button" class="date-quick-btn" data-days="-2">前天</button>
                    </div>
                    <input type="date" class="form-control" id="date-picker" value="{{ $transaction->transaction_date->format('Y-m-d') }}">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirm-date">确定</button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
    <style>
        /* 记账表单样式 */
        .app-container {
            padding-bottom: 0px;
        }
        .form-container {
            background: white;
            border-radius: 20px 20px 0 0;
            min-height: calc(100vh - 120px);
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #2d3748;
        }

        .form-input {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e2e8f0;
            border-radius: 12px;
            font-size: 16px;
            transition: all 0.3s ease;
            background: #f8f9fa;
        }

        .form-input:focus {
            outline: none;
            border-color: #667eea;
            background: white;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }

        /* 输入区域 */
        .input-area {
            display: flex;
            align-items: center;
            background: white;
            padding: 15px 20px;
            margin-bottom: 10px;
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .description-input {
            font-size: 15px;
            color: #4a5568;
            transition: all 0.3s ease;
            border: none;
            outline: none;
            flex-grow: 1;
            background: transparent;
        }

        .description-input::placeholder {
            color: #a0aec0;
        }

        .amount-display {
            font-size: 20px;
            font-weight: 700;
            color: #38a169;
            background: linear-gradient(135deg, #51cf66 0%, #38a169 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            padding: 0 15px;
        }

        .receipt-upload {
            background: linear-gradient(135deg, #f8f9fa 0%, #e2e8f0 100%);
            width: 40px;
            height: 40px;
            border: none;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            color: #4a5568;
            font-size: 18px;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .receipt-upload:hover {
            transform: translateY(-2px) scale(1.05);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            color: #38a169;
        }

        /* 计算器 */
        .calculator {
            /*background: linear-gradient(135deg, rgba(240, 255, 244, 0.95) 0%, rgba(226, 242, 228, 0.95) 100%);*/
            /*backdrop-filter: blur(10px);*/
            /*border-radius: 20px 20px 0 0;*/
            /*padding: 25px 20px;*/
            /*box-shadow: 0 -4px 20px rgba(0,0,0,0.08);*/
            margin-top: auto;
        }

        .calculator-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 12px;
        }

        .calculator-grid .equals {
            grid-column: span 2;
        }

        .calculator-btn {
            height: 60px;
            border: none;
            border-radius: 16px;
            font-size: 20px;
            font-weight: 600;
            background: white;
            color: #4a5568;
            box-shadow: 0 4px 10px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
        }

        .calculator-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(0,0,0,0.1);
        }

        .calculator-btn:active {
            transform: translateY(1px);
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .calculator-btn.btn-clicked {
            animation: buttonClick 0.15s ease-in-out;
        }

        @keyframes buttonClick {
            0% { transform: scale(1); }
            50% { transform: scale(0.95); }
            100% { transform: scale(1); }
        }

        .calculator-btn.operator {
            background: linear-gradient(135deg, #f0fff4 0%, #dcfce7 100%);
            color: #38a169;
            font-weight: 700;
        }

        .calculator-btn.date {
            background: linear-gradient(135deg, #e6fffa 0%, #d0f7ef 100%);
            color: #319795;
            font-weight: 600;
            box-shadow: 0 4px 12px rgba(49, 151, 149, 0.2);
        }

        .calculator-btn.date:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 18px rgba(49, 151, 149, 0.3);
        }

        .calculator-btn.equals {
            background: linear-gradient(135deg, #51cf66 0%, #38a169 100%);
            color: white;
            font-weight: 700;
            box-shadow: 0 4px 15px rgba(56, 161, 105, 0.3);
        }

        .calculator-btn.equals:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(56, 161, 105, 0.4);
        }

        .calculator-btn#cancel-btn {
            background: linear-gradient(135deg, #edf2f7 0%, #cbd5e0 100%);
            color: #4a5568;
            font-weight: 600;
            box-shadow: 0 4px 12px rgba(74, 85, 104, 0.2);
        }

        .calculator-btn#cancel-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 18px rgba(74, 85, 104, 0.3);
        }

        .amount-display {
            background: linear-gradient(135deg, #ff6b6b 0%, #e53e3e 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .receipt-upload:hover {
            color: #e53e3e;
        }

        /* 日期选择器样式 */
        .date-picker-container {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .date-quick-options {
            display: flex;
            justify-content: space-between;
            gap: 10px;
            margin-bottom: 10px;
        }

        .date-quick-btn {
            flex: 1;
            background: linear-gradient(135deg, #f0fff4 0%, #dcfce7 100%);
            border: none;
            border-radius: 12px;
            padding: 10px 0;
            font-weight: 600;
            color: #38a169;
            transition: all 0.3s ease;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .date-quick-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(56, 161, 105, 0.2);
        }

        .btn-primary {
            background: linear-gradient(135deg, #51cf66 0%, #38a169 100%);
            border: none;
            border-radius: 12px;
            padding: 10px 25px;
            font-weight: 600;
            box-shadow: 0 4px 15px rgba(56, 161, 105, 0.3);
            transition: all 0.3s ease;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(56, 161, 105, 0.4);
        }

    </style>
@endpush

@push('scripts')
<script>
$(document).ready(function() {
    let selectedCategoryId = {{ $transaction->category_id }};
    let selectedSubCategoryId = {{ $transaction->sub_category_id ?? 'null' }};
    let selectedCategoryId_ori = selectedCategoryId;
    let selectedSubCategoryId_ori = selectedSubCategoryId;
    let currentAmount = '{{ $transaction->amount }}';
    let currentOperator = null;
    let previousValue = null;
    let newInput = true;
    let selectedDate = '{{ $transaction->transaction_date->format("Y-m-d") }}';
    let calculationInProgress = false;

    // 调试信息
    console.log('编辑页面加载时的数据:');
    console.log('交易ID:', $('#transaction-id').val());
    console.log('当前分类ID:', selectedCategoryId);
    console.log('当前子分类ID:', selectedSubCategoryId);
    console.log('当前类型:', $('#transaction-type').val());

    // 切换收入支出标签
    const expenseTab = $('#expense-tab');
    const incomeTab = $('#income-tab');
    const expenseCategories = $('#expense-categories');
    const incomeCategories = $('#income-categories');

    function switchToExpense() {
        console.log('切换到支出');
        expenseTab.addClass('active');
        incomeTab.removeClass('active');
        expenseCategories.show();
        incomeCategories.hide();
        $('#transaction-type').val('expense');
        $('#record-form-title').text('编辑支出');
        hideAllSubcategories();

        // 选中第一个支出分类
        const firstExpenseCategory = expenseCategories.find('.category-item').first();
        if (firstExpenseCategory.length) {
            expenseCategories.find('.category-item').removeClass('active');
            firstExpenseCategory.addClass('active');
            selectedCategoryId = firstExpenseCategory.data('category-id');
            selectedSubCategoryId = null;

            // 显示对应的二级分类
            selectSubCategoryAuto('expense', 0)
        }
    }

    function switchToIncome() {
        incomeTab.addClass('active');
        expenseTab.removeClass('active');
        incomeCategories.show();
        expenseCategories.hide();
        $('#transaction-type').val('income');
        $('#record-form-title').text('编辑收入');
        hideAllSubcategories();

        // 选中第一个收入分类
        const firstIncomeCategory = incomeCategories.find('.category-item').first();
        if (firstIncomeCategory.length) {
            incomeCategories.find('.category-item').removeClass('active');
            firstIncomeCategory.addClass('active');
            selectedCategoryId = firstIncomeCategory.data('category-id');
            selectedSubCategoryId = null;

            // 显示对应的二级分类
            selectSubCategoryAuto('income', 0)
        }
    }

    function selectSubCategoryAuto(type, sub_id = 0) {
        const subcategorySelector = $(`#subcategory-${type}-${selectedCategoryId}`);
        subcategorySelector.show();
        var firstSubCategory;
        if (! sub_id) {
            if (selectedSubCategoryId_ori && selectedCategoryId === selectedCategoryId_ori) sub_id = selectedSubCategoryId_ori;
        }
        if (sub_id) {
            firstSubCategory = subcategorySelector.find(`.subcategory-item[data-subcategory-id="${sub_id}"]`)
        }
        if (!firstSubCategory || !firstSubCategory.length) {
            firstSubCategory = subcategorySelector.find('.subcategory-item').first();
        }

        if (firstSubCategory.length) {
            firstSubCategory.addClass('active');
            selectedSubCategoryId = firstSubCategory.data('subcategory-id');
            showSelectInfo()
        }
    }

    function showSelectInfo() {
        // 更新已选分类信息
        const categoryName = $('.category-item.active').data('category');
        const subcategoryName = $('.subcategory-item.active').data('subcategory');
        $('#category-selected-info').text(`已选: ${categoryName} - ${subcategoryName}`).show();
    }

    expenseTab.click(switchToExpense);
    incomeTab.click(switchToIncome);

    // 隐藏所有二级分类
    function hideAllSubcategories() {
        $('.subcategory-selector').hide();
        $('.subcategory-item').removeClass('active');
        $('#category-selected-info').hide();
    }

    // 一级分类选择
    $('.category-item').click(function() {
        const parent = $(this).parent();
        parent.find('.category-item').removeClass('active');
        $(this).addClass('active');

        selectedCategoryId = $(this).data('category-id');
        if (selectedSubCategoryId === selectedSubCategoryId_ori) {
            selectedSubCategoryId = selectedSubCategoryId_ori;
        } else {
            selectedSubCategoryId = 0;
        }

        hideAllSubcategories();
        selectSubCategoryAuto($(this).data('type'), selectedSubCategoryId)
    });

    // 二级分类选择
    $('.subcategory-item').click(function() {
        const parent = $(this).parent();
        parent.find('.subcategory-item').removeClass('active');
        $(this).addClass('active');

        selectedSubCategoryId = $(this).data('subcategory-id');

        // 显示对应的二级分类
        showSelectInfo()
    });

    // 更新金额显示
    function updateAmountDisplay() {
        document.getElementById('amount-display').textContent = currentAmount;
    }

    // 更新日期显示
    function updateDateDisplay() {
        const dateObj = new Date(selectedDate);
        const month = dateObj.getMonth() + 1;
        const day = dateObj.getDate();
        document.getElementById('date-display').textContent = month + '.' + day;
        document.getElementById('record-date').value = selectedDate;
    }

    // 初始化日期显示
    updateDateDisplay();

    // 计算器功能
    $('.calculator-btn').click(function() {
        const value = $(this).data('value');

        // 添加按钮点击动画效果
        $(this).addClass('btn-clicked');
        setTimeout(() => {
            $(this).removeClass('btn-clicked');
        }, 150);

        if (value !== undefined) {
            handleNumberOrOperator(value);
        }
    });

    // 处理数字或运算符输入
    function handleNumberOrOperator(value) {
        // 处理数字和小数点
        currentAmount = currentAmount.toString();
        if (!isNaN(value) || value === '.') {
            if (newInput) {
                currentAmount = value === '.' ? '0.' : value;
                newInput = false;
            } else {
                // 确保只有一个小数点
                if (value === '.' && currentAmount.includes('.')) {
                    return;
                }
                // 限制小数点后两位
                if (currentAmount.includes('.') && currentAmount.split('.')[1].length >= 2 && value !== '.') {
                    return;
                }
                currentAmount += value;
            }
            updateAmountDisplay();
        }
        // 处理运算符
        else if (value === '+' || value === '-') {
            if (calculationInProgress) {
                // 如果已经有一个计算在进行中，先计算结果
                calculate();
            }
            previousValue = parseFloat(currentAmount);
            currentOperator = value;
            newInput = true;
            calculationInProgress = true;
        }

        // 确保计算器按钮在任何情况下都能响应
        $('.calculator-btn').removeClass('btn-clicked');

    }

    // 计算结果
    function calculate() {
        if (!calculationInProgress) return;

        const currentVal = parseFloat(currentAmount);
        let result;

        if (currentOperator === '+') {
            result = previousValue + currentVal;
        } else if (currentOperator === '-') {
            result = previousValue - currentVal;
        }

        // 确保结果为正数
        result = Math.max(0, result);

        // 限制小数点后两位
        currentAmount = result.toString();
        updateAmountDisplay();

        // 重置计算状态
        previousValue = null;
        currentOperator = null;
        calculationInProgress = false;
        newInput = true;
    }

    // 删除按钮功能
    $('#delete-btn').click(function() {
        if (currentAmount.length > 1) {
            currentAmount = currentAmount.slice(0, -1);
        } else {
            currentAmount = '0';
        }
        updateAmountDisplay();
        newInput = false;
    });

    // 日期选择
    document.getElementById('date-btn').addEventListener('click', function() {
        $('#dateModal').modal('show');
    });

    // 快速日期选择
    document.querySelectorAll('.date-quick-btn').forEach(function(btn) {
        btn.addEventListener('click', function() {
            const days = parseInt(this.getAttribute('data-days'));
            const date = new Date();
            date.setDate(date.getDate() + days);

            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');

            selectedDate = `${year}-${month}-${day}`;
            document.getElementById('date-picker').value = selectedDate;
        });
    });

    // 确认日期选择
    document.getElementById('confirm-date').addEventListener('click', function() {
        selectedDate = document.getElementById('date-picker').value;
        updateDateDisplay();
        $('#dateModal').modal('hide');
    });

    // 取消按钮和关闭按钮点击事件
    $('.btn-secondary, .close').click(function() {
        $('#dateModal').modal('hide');
    });

    // 上传收据
    document.getElementById('receipt-upload').addEventListener('click', function() {
        // 这里可以添加上传收据的功能
        alert('上传收据功能暂未实现');
    });

    // 保存按钮
    document.getElementById('saveBtn').addEventListener('click', function(e) {
        e.preventDefault();

        // 如果有计算在进行中，先计算结果
        if (calculationInProgress) {
            calculate();
        }

        // 验证表单
        if (!selectedCategoryId || !selectedSubCategoryId) {
            alert('请选择分类');
            return;
        }

        if (!currentAmount || parseFloat(currentAmount) <= 0) {
            alert('请输入有效金额');
            return;
        }

        // 收集表单数据
        const formData = {
            _token: document.querySelector('input[name="_token"]').value,
            _method: 'PUT',
            type: document.getElementById('transaction-type').value,
            amount: currentAmount,
            category_id: selectedCategoryId,
            sub_category_id: selectedSubCategoryId,
            transaction_date: document.getElementById('record-date').value,
            description: document.getElementById('record-note').value,
            ai_category: '',
            ai_subcategory: '',
            transaction_id: document.getElementById('transaction-id').value
        };

        // 发送AJAX请求
        fetch(`/transaction/${formData.transaction_id}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': formData._token
            },
            body: JSON.stringify(formData)
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    window.location.href = '/';
                } else {
                    if (data.errors) {
                        let errorMessage = '';
                        for (const key in data.errors) {
                            errorMessage += data.errors[key].join('\n') + '\n';
                        }
                        alert(errorMessage);
                    } else {
                        alert('保存失败，请重试');
                    }
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('发生错误，请重试');
            });
    });
});
</script>
@endpush
